import {
  getTeamByPage,
  addTeam,
  updateTeam,
  delTeam,
  exportTeam,
  getProjectName,
} from '@/services/baseData/team';
import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Popover, Select, Tooltip } from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { Ellipsis } from '@/components/Ellipsis';
import { NavLink } from 'react-router-dom';
const Team: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [optionsAdd, setOptionsAdd] = useState([]);
  const [defaultProjectName, setDefaultProjectName] = useState('');
  const [addTeamInfo, setAddTeamInfo] = useState({});
  const [form] = Form.useForm();

  const ref = useRef(null);

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 30,
    },
    {
      title: '团队名称',
      dataIndex: 'teamName',
      width: 90,
      align: 'center',
      sorter: true,

      render: (text, record) => {
        return <div>{text}</div>;
      },
    },
    {
      title: '团队编号',
      dataIndex: 'teamCode',
      width: 70,
      align: 'center',
      sorter: true,

      render: (text, record) => [
        <NavLink
          to={{ pathname: '/systemSetting/teamInfo/', state: { id: record.id } }}
          key={record.id}
        >
          {text}
        </NavLink>,
      ],
    },
    {
      title: '启用状态',
      dataIndex: 'state',
      width: 90,
      align: 'center',
      sorter: true,
      search: false,
      render: (text) => {
        return (<div>{text === 1 ? '启用' : '禁用'}</div>)
      }
    },
    // {
    //   title: '项目名称',
    //   dataIndex: 'projectName',
    //   width: 70,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    {
      title: '备注',
      dataIndex: 'memo',
      width: 90,
      align: 'center',
      sorter: true,
      search: false,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
      width: 100,
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
      width: 90,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },

    // {
    //   title: '预留',
    //   dataIndex: 'reserved',
    //   width: 90,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    // {
    //   title: '流水号',
    //   dataIndex: 'serialNo',
    //   width: 90,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 60,
      align: 'center',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑');
            form.setFieldsValue({
              memo: record.memo,
              reserved: record.reserved,
              serialNo: record.serialNo,
              teamName: record.teamName,
              projectName: record.projectName,
              teamCode: record.teamCode,
              infoId: record.infoId,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                const res = await delTeam({ id: record.id });
                if (res != null) message.success('删除成功！');
                actionRef.current?.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const handleSubmit = async () => {
    setConfirmLoading(true);

    if (formTitle == '新建') {
      form
        .validateFields()
        .then(async (value) => {
          const paramsForm = form.getFieldsValue();
          // paramsForm.infoId = addTeamInfo.info.value;
          //  paramsForm.projectName = addTeamInfo.info.label;
          //console.log(paramsForm, 'addTeaparamsFormmInfo');
          const result = await addTeam(paramsForm);
          if (result != null) {
            message.success('添加成功');
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current?.reload();
        })
        .catch((err) => {
          setConfirmLoading(false);
          console.log(err);
        });
    } else {
      form
        .validateFields()
        .then(async () => {
          const paramsForm = form.getFieldsValue();
          const result = await updateTeam(paramsForm);

          if (result != null) {
            message.success('修改成功');
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current?.reload();
        })
        .catch((error) => {
          setConfirmLoading(false);
          console.log(error);
        });
    }
  };

  const teamExplanation = (
    <div style={{ fontSize: '14px', padding: '5px' }}>
      有效团队需要满足以下条件：<br />
      条件1：团队中包含所有必填角色<br />
      条件2：团队中只能包含一名项目经理、生产经理、技术经理
    </div>
  )

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="项目团队查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        revalidateOnFocus={false}
        toolBarRender={(action, { selectedRows }) => [
          <>
            <Popover content={teamExplanation} title="启用状态">
              <QuestionCircleOutlined />
            </Popover>
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                setCreateOrUpdate(false);
                setFormTitle('新建');
                form.resetFields();
                setModalVisit(true);
              }}
              type="primary"
            >
              新建
          </Button>
          </>
          // <Button
          //   key="button"
          //   icon={<PlusOutlined />}
          //   onClick={() => {
          //     const filters = filterTran(ref.current.getFieldsValue());
          //     exportTeam({
          //       current: 1,
          //       pageSize: 5000,
          //       filters: filters,
          //     }).then((res) => {
          //       const aLink = document.createElement('a');
          //       document.body.appendChild(aLink);
          //       aLink.style.display = 'none';
          //       aLink.href = window.URL.createObjectURL(res);
          //       aLink.setAttribute('download', `Team.xlsx`);
          //       aLink.click();
          //       document.body.removeChild(aLink);
          //     });
          //   }}
          //   type="primary"
          // >
          //   导出
          // </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const sorters = sortTran(sort);
          const filters = filterTran(params);
          const result = await getTeamByPage({ ...params, sorters: sorters, filters: filters });

          const getProName = await getProjectName(null);
          // 有数据的话，执行后续；否则页面数据显示出错
          if (getProName.data.length != 0) {
            const value2: { value: any, label: any; }[] = [];
            getProName.data.map((item: any, index: Number) => {
              value2.push({ value: item.infoId, label: item.projectName });
            });
            setDefaultProjectName(value2[0].label || '');
            setOptionsAdd(value2);
          }

          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 2000, y: 350 }}
        rowSelection={{}}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          {/* <Form.Item
            label="项目名称"
            name="projectName"
            rules={[{ required: true, message: '请输入项目名称！' }]}
          >
            <Select
              placeholder="请选择项目信息"
              disabled={createOrUpdate}
              onChange={(value, label) => {
                setAddTeamInfo({ info: label });
              }}
              options={optionsAdd}
            />
          </Form.Item> */}
          <Form.Item
            label="团队名称"
            name="teamName"
            rules={[{ required: true, message: '请输入团队名称!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            hidden={true}
            label="团队编号"
            name="teamCode"
          //rules={[{ required: true, message: 'Please input your teamCode!' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>

          {/* <Form.Item
            label="流水号"
            name="serialNo"
            //rules={[{ required: true, message: 'Please input your serialNo!' }]}
          >
            <Input />
          </Form.Item> */}
          <Form.Item
            label="备注"
            name="memo"
          //rules={[{ required: true, message: 'Please input your memo!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            hidden={true}
            label="预留"
            name="reserved"
          // rules={[{ required: true, message: 'Please input your reserved!' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>
          <Form.Item
            label="项目id"
            name="infoId"
            hidden={true}
          // rules={[{ required: true, message: 'Please input your infoId!' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default Team;
